package com.finalministry.db.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.hibernate.HibernateException;

import com.finalministry.db.dao.AbstractDAO;
import com.finalministry.db.dao.DataAccessLayerException;
import com.finalministry.db.objects.address.Country;

@SuppressWarnings("rawtypes")
public class CountryDAO extends AbstractDAO {

	private static final String TABLENAME = "country";

	public CountryDAO() {
		super();
	}

	/**
	 * Insert a new Country into the database.
	 * 
	 * @param Country
	 * @return persisted ID
	 * @throws DataAccessLayerException
	 */
	public Country merge(Country country) throws DataAccessLayerException {

		return (Country) super.merge(country);
	}

	/**
	 * Delete a detached Country from the database.
	 * 
	 * @param Country
	 */
	public void delete(Country country) throws DataAccessLayerException {

		super.delete(country);
	}

	/**
	 * Find an Country by its primary key.
	 * 
	 * @param id
	 * @return
	 */
	public Country find(Long id) throws DataAccessLayerException {

		return (Country) super.find(Country.class, id);
	}

	/**
	 * Finds all Countrys in the database.
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Country> findAll() throws DataAccessLayerException {

		return super.findAll(Country.class);
	}

	/**
	 * Get table name
	 */
	@Override
	protected String getTableName() {

		return TABLENAME;
	}

	public Country getByIsoCode3(String isocode3) {

		try {
			startOperation();

			Query query = em.createNativeQuery("select * from country where isocode3 = " + isocode3);
			Country country = (Country) query.getSingleResult();
			em.getTransaction().commit();
			return country;
		} catch (HibernateException e) {
			handleException(e);
			return null;
		} finally {
			em.close();
		}
	}
}
